package cn.action;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;

import cn.biz.ConfigurationBiz;
import cn.biz.GoodsBiz;
import cn.biz.OrdergoodsBiz;
import cn.biz.OrdersBiz;
import cn.biz.UserBiz;
import cn.entity.Brand;
import cn.entity.Goods;
import cn.entity.Ordergoods;
import cn.entity.Orders;
import cn.entity.User;
import cn.util.CreatOrderNum;
import cn.util.UserUtil;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;

public class OrdersAction implements Action {
	private OrdersBiz ordersBiz;
	private GoodsBiz goodsBiz;
	private OrdergoodsBiz ordergoodsBiz;
	private ConfigurationBiz configurationBiz;
	private UserBiz userBiz;
	private Orders newOrder;
	private String resultStr = "";
	private Goods newOrderGood; //订单商品(单个商品)
	private List<Orders> Olist = new ArrayList<Orders>();
	private Orders orders;
	private List<Ordergoods> orderGoodsList = new ArrayList();
	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
	SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
	UserUtil userUtil = new UserUtil();
	// 订单相关信息
	private int amount;
	private Integer gid;
	private Integer[] goodIds;
	private String orderNum;
	private String orderStatus;
	private Brand brand;
	
	public List<Ordergoods> getOrderGoodsList() {
		return orderGoodsList;
	}

	public void setOrderGoodsList(List<Ordergoods> orderGoodsList) {
		this.orderGoodsList = orderGoodsList;
	}

	public String getResultStr() {
		return resultStr;
	}

	public void setResultStr(String resultStr) {
		this.resultStr = resultStr;
	}

	public ConfigurationBiz getConfigurationBiz() {
		return configurationBiz;
	}

	public void setConfigurationBiz(ConfigurationBiz configurationBiz) {
		this.configurationBiz = configurationBiz;
	}
	
	public Goods getNewOrderGood() {
		return newOrderGood;
	}

	public void setNewOrderGood(Goods newOrderGood) {
		this.newOrderGood = newOrderGood;
	}

	public OrdergoodsBiz getOrdergoodsBiz() {
		return ordergoodsBiz;
	}

	public void setOrdergoodsBiz(OrdergoodsBiz ordergoodsBiz) {
		this.ordergoodsBiz = ordergoodsBiz;
	}

	public Orders getNewOrder() {
		return newOrder;
	}

	public void setNewOrder(Orders newOrder) {
		this.newOrder = newOrder;
	}

	public Map<String, Object> getSession() {
		return ActionContext.getContext().getSession();
	}

	public User getSessionUser() {
		return (User) getSession().get("loginUser");
	}

	public OrdersBiz getOrdersBiz() {
		return ordersBiz;
	}

	public void setOrdersBiz(OrdersBiz ordersBiz) {
		this.ordersBiz = ordersBiz;
	}

	public GoodsBiz getGoodsBiz() {
		return goodsBiz;
	}

	public void setGoodsBiz(GoodsBiz goodsBiz) {
		this.goodsBiz = goodsBiz;
	}

	public UserBiz getUserBiz() {
		return userBiz;
	}

	public void setUserBiz(UserBiz userBiz) {
		this.userBiz = userBiz;
	}

	public List<Orders> getOlist() {
		return Olist;
	}

	public void setOlist(List<Orders> olist) {
		Olist = olist;
	}

	public Orders getOrders() {
		return orders;
	}

	public void setOrders(Orders orders) {
		this.orders = orders;
	}

	public int getAmount() {
		return amount;
	}

	public void setAmount(int amount) {
		this.amount = amount;
	}

	public Integer getGid() {
		return gid;
	}

	public void setGid(Integer gid) {
		this.gid = gid;
	}
	
	
	public Integer[] getGoodIds() {
		return goodIds;
	}

	public void setGoodIds(Integer[] goodIds) {
		this.goodIds = goodIds;
	}

	public String getOrderNum() {
		return orderNum;
	}

	public void setOrderNum(String orderNum) {
		this.orderNum = orderNum;
	}

	public String getOrderStatus() {
		return orderStatus;
	}

	public void setOrderStatus(String orderStatus) {
		this.orderStatus = orderStatus;
	}

	public Brand getBrand() {
		return brand;
	}

	public void setBrand(Brand brand) {
		this.brand = brand;
	}

	//进入用户订单管理界面
	public String userOrders(){
		return SUCCESS;
	}
	
	//获取当前登陆用户的所有订单信息
	public String getOrdersListByBuyer() {
		Olist = ordersBiz.getOrdersListByBuyer(getSessionUser());
		StringBuffer orderJson = new StringBuffer("{result:[");
		try{
			if(Olist.size()>0){
				int j = 0;
				for(Orders o : Olist){//遍历所有用户当前订单
					if (j > 0) {
						orderJson.append(",");
					}
					orderJson.append("{");
					//创建日期
					orderJson.append("createDate:'").append(sdf1.format(sdf.parse(o.getNum().substring(0, 8)))).append("',");
					//订单编号
					orderJson.append("orderNo:'").append(o.getNum()).append("',");
					//获取订单关联的的商品的商品快照
					//这里需要调用orderGoodsBiz里的方法, 根据订单的id(不是订单编号)获取该订单下的所有商品快照;
					List<Ordergoods> ordergoods = ordergoodsBiz.getOrdergoodsByOrderId(o.getId()); 
					//System.out.println("订单id: "+o.getId()+", 找到商品数: "+ordergoods.size());
					orderJson.append("goods:[");
					if(ordergoods.size()>0){
						int k = 0;
						StringBuffer goodsStr = new StringBuffer("");
						for(int i=0;i<ordergoods.size();i++){
							if(k>0){
								goodsStr.append(",");
							}
							goodsStr.append("{");
							goodsStr.append("name:'").append(ordergoods.get(i).getName()).append("',");
							goodsStr.append("price:'").append(ordergoods.get(i).getGoods().getPrice()).append("',");
							String img = ordergoods.get(i).getGoods().getImg();
							if(StringUtils.isBlank(img)) {
								img = "images/pic1.jpg";
							}
							goodsStr.append("img:'").append(img).append("',");
							goodsStr.append("amount:").append(ordergoods.get(i).getAmount());
							goodsStr.append("}");
							k++;
						}
						orderJson.append(goodsStr);
					}
					orderJson.append("],");
					//订单总价
					orderJson.append("totalPrice:").append(o.getMoney()).append(",");
					//卖家
					orderJson.append("seller:'").append(ordergoods.get(0).getGoods().getUser().getName()).append("',");
					//订单状态
					orderJson.append("status:'").append(configurationBiz.getStatusByStatusCode(o.getStatus()).getValue1()).append("',");
					//下一步可操作
					if(o.getStatus().equals("001")){//待付款状态 可操作的行为为"付款"     备注:"可用状态"由多个参数构成 a-b-c, a为显示在按钮上的文本, b为是否显示成一个按钮, c为点击按钮的下一步状态, 多个按钮间用,分割
						orderJson.append("avaliableStatus:'").append("付款-true-002").append("'");
					}else if(o.getStatus().equals("002")){//已付款状态
						//无任何操作
						orderJson.append("avaliableStatus:'").append("none-false-none").append("'");
					}else if(o.getStatus().equals("003")){//卖家已发货, 待买家确认
						//无任何操作
						orderJson.append("avaliableStatus:'").append("确认收货-true-004").append("'");
					}else if(o.getStatus().equals("004")){//买家已经确认收货
						//无任何操作
						orderJson.append("avaliableStatus:'").append("已收货-false-004").append("'");
					}
					orderJson.append("}");
					j++;
				}
			}
			orderJson.append("]}");
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		resultStr = "(" + orderJson.toString() + ")";
		return SUCCESS;
	}

	// 跳转到 购买商品的订单收件人信息确认页面(单件商品)
	public String checkOrder() {
		try{
			Map<String, Object> session = getSession();
			//System.out.println("amount: " + amount);
			//System.out.println("gid: " + gid[0]);
			//System.out.println("用户是否登陆: " + userUtil.checkUserLogin());
			if (!userUtil.checkUserLogin()) {// 用户未登陆, 返回UNLOGGED
				// 跳转到登陆页面
				return "UNLOGGED";
			} else {// 如果用户登陆了
				Orders odr = new Orders();//订单
				Ordergoods og = new Ordergoods();//商品快照
				
				//加入商品(该步骤作废, 使用保存商品快照形式)
				//odr.setGoods(goodsBiz.getGoodsById(gid[0]));
				
				//以当前商品信息创建商品快照, 并和当前订单关联
				og.setOrders(odr);//关联工单
				og.setGoods(goodsBiz.getGoodsById(gid));//商品
				og.setName(goodsBiz.getGoodsById(gid).getGoodsname());//商品名
				og.setRemark(goodsBiz.getGoodsById(gid).getRemark());//商品描述
				og.setPrice(goodsBiz.getGoodsById(gid).getPrice());//商品价格
				og.setAmount(amount);//商品数量
				og.setUser(goodsBiz.getGoodsById(gid).getUser());//商品卖家
				//odr.setOrdergoodses(goods);
				// 设置买家
				odr.setUser(getSessionUser());
				//设置价格
				odr.setMoney(amount * goodsBiz.getGoodsById(gid).getPrice());
				//设置状态为"待付款"
				odr.setStatus("001");
				//设置订单编号
				String orderno = CreatOrderNum.getOrderNumByUid(getSessionUser().getId());
				odr.setNum(orderno);
				//设置删除标记
				odr.setIsDelete(0);
				//设置创建日期
				odr.setCreDate(new Date());
				//订单先保存
				ordersBiz.insert(odr);
				ordergoodsBiz.insert(og);
				session.put("newOrder", odr);
				session.put("newOrderGood", goodsBiz.getGoodsById(gid));
				session.put("goodAmount", amount);
				// 跳转到订单详情填写页面
				
			}
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return "CHECKORDER";
	}
	
	//买家 - 支付订单
	public String payTheOrder(){
		Map<String, Object> session = getSession();
		if (!userUtil.checkUserLogin()) {// 用户未登陆, 返回UNLOGGED
			return "UNLOGGED";
		}else{//付款操作
			Orders tempOrder = (Orders)session.get("newOrder");
			//设置收件人名字
			tempOrder.setReceiver(newOrder.getReceiver());
			//设置收件人电话
			tempOrder.setPhone(newOrder.getPhone());
			//设置收件人地址
			tempOrder.setAddress(newOrder.getAddress()); 
			//设置订单状态为"已付款, 待发货"
			tempOrder.setStatus("002");
			//更新保存订单
			ordersBiz.update(tempOrder);
			//session中移除newOrder
			session.remove("newOrder");
			return "PAID";
		}
	}
	//买家 - 支付多份订单
	public String payOrders(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String[] ordersNo = request.getParameter("awaitOrdersNo").split(",");
		String address = request.getParameter("address");
		String receiver = request.getParameter("receiver");
		String phone = request.getParameter("phone");
		for(String orderno:ordersNo){
			if(!orderno.equals("")){
				List<Orders> orders = ordersBiz.getOrdersByOrderNum(orderno);
				orders.get(0).setAddress(address);
				orders.get(0).setReceiver(receiver);
				orders.get(0).setPhone(phone);
				orders.get(0).setStatus("002");
				ordersBiz.update(orders.get(0));
			}
		}
		
		
		return "PAID";
	}
	
	//从用户中心发起未付款订单付款
	public String payFromeUserOrder(){
		orders = ordersBiz.getOrdersByOrderNum(orderNum).get(0);
		return SUCCESS;
	}
	
	//从用户中心发起订单确认收货
	public String confirmPayOrder() {
		orders = ordersBiz.getOrdersByOrderNum(orderNum).get(0);
		return SUCCESS;
	}
	
	//根据订单号改变订单状态
	public String changeStatus(){
		Orders orders = ordersBiz.getOrdersByOrderNum(orderNum).get(0);
		if(!orders.getUser().getId().equals(getSessionUser().getId())) {
			resultStr = "{\"data\":\"errorUser\"}";
			return SUCCESS;
		}
		orders.setStatus(orderStatus);
		try {
			ordersBiz.update(orders);
			resultStr = "{\"data\":\"success\"}";
		} catch (Exception e) {
			e.printStackTrace();
			resultStr = "{\"data\":\"error\"}";
		}
		return SUCCESS;
	}
	
	//卖家 - 进入当前登陆用户为卖家的卖家订单管理界面
	public String getOrderBySeller(){
		/*Olist = ordersBiz.getOrdersListBySeller(getSessionUser());
		System.out.println("卖家订单: "+Olist.size());
		for (Orders orders : Olist) {
			System.out.println(" orderaction getOrderBySeller 卖家获取订单号:"+orders.getNum());
		}*/
		return SUCCESS;
	}
	
	//卖家 - 获取当前登陆用户为卖家的订单(json)
	public String getSellerOrdersAsJson(){
		Olist = ordersBiz.getOrdersListBySeller(getSessionUser());
		StringBuffer orderJson = new StringBuffer("{result:[");
		try{
			if(Olist.size()>0){
				int j = 0;
				for(Orders o : Olist){//遍历所有用户当前订单
					if (j > 0) {
						orderJson.append(",");
					}
					orderJson.append("{");
					//下单日期
					orderJson.append("createDate:'").append(sdf1.format(sdf.parse(o.getNum().substring(0, 8)))).append("',");
					//订单编号
					orderJson.append("orderNo:'").append(o.getNum()).append("',");
					//获取订单关联的的商品的商品快照
					//这里需要调用orderGoodsBiz里的方法, 根据订单的id(不是订单编号)获取该订单下的所有商品快照;
					List<Ordergoods> ordergoods = ordergoodsBiz.getOrdergoodsByOrderId(o.getId()); 
					//System.out.println("订单id: "+o.getId()+", 找到商品数: "+ordergoods.size());
					orderJson.append("goods:[");
					if(ordergoods.size()>0){
						int k = 0;
						StringBuffer goodsStr = new StringBuffer("");
						for(int i=0;i<ordergoods.size();i++){
							if(k>0){
								goodsStr.append(",");
							}
							goodsStr.append("{");
							goodsStr.append("name:'").append(ordergoods.get(i).getName()).append("',");
							goodsStr.append("price:'").append(ordergoods.get(i).getGoods().getPrice()).append("',");
							String img = ordergoods.get(i).getGoods().getImg();
							if(StringUtils.isBlank(img)) {
								img = "images/pic1.jpg";
							}
							goodsStr.append("img:'").append(img).append("',");
							goodsStr.append("amount:").append(ordergoods.get(i).getAmount());
							goodsStr.append("}");
							k++;
						}
						orderJson.append(goodsStr);
					}
					orderJson.append("],");
					//订单总价
					orderJson.append("totalPrice:").append(o.getMoney()).append(",");
					//买家
					orderJson.append("buyer:'").append(o.getUser().getName()).append("',");
					//订单状态
					orderJson.append("status:'").append(configurationBiz.getStatusByStatusCode(o.getStatus()).getValue1()).append("',");
					//下一步可操作
					if(o.getStatus().equals("001")){//待付款状态  对卖家来说, 没什么好操作的    备注:"可用状态"由多个参数构成 a-b-c, a为显示在按钮上的文本, b为是否显示成一个按钮, c为点击按钮的下一步状态, 多个按钮间用,分割
						orderJson.append("avaliableStatus:'").append("none-false-001").append("'");
					}else if(o.getStatus().equals("002")){//已付款状态, 买家已付款, 下一步等卖家发货
						//无任何操作
						orderJson.append("avaliableStatus:'").append("发货-true-003").append("'");
					}else if(o.getStatus().equals("003")){//已发货状态, 卖家已发货, 下一步等买家确认
						//无任何操作
						orderJson.append("avaliableStatus:'").append("none-false-none").append("'");
					}else if(o.getStatus().equals("004")){//买家已经确认收货
						//无任何操作
						orderJson.append("avaliableStatus:'").append("none-false-none").append("'");
					}
					orderJson.append("}");
					j++;
				}
			}
			orderJson.append("]}");
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		resultStr = "(" + orderJson.toString() + ")";
		return SUCCESS;
	}
	
	//卖家 - 改变订单状态
	public String changeOrderStatusAsSeller(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String orderNum = request.getParameter("orderNum");
		String []settings = request.getParameter("settings").split("-");
		//System.out.println(orderNum+" "+settings);
		//待操作订单
		orders = ordersBiz.getOrdersByOrderNum(orderNum).get(0);
		//待操作订单关联的商品
		orderGoodsList = ordergoodsBiz.getOrdergoodsByOrderId(orders.getId());
		if(settings[2].equals("003") && settings[0].equals("发货")){//订单切换状态为003且操作是"发货" 则跳转至 检查订单发货信息页
			return "sellerCheckSendingInfo";
		}
		return null;
	}
	
	//卖家 - 确定发货操作
	public String sendTheOrder(){
		String recieverOrderNum = newOrder.getNum();
		String recieverAddress = newOrder.getAddress();
		String receiver = newOrder.getReceiver();
		String recieverPhone = newOrder.getPhone();
		//System.out.println(recieverOrderNum+" "+receiver+" "+recieverAddress);
		Orders odr = ordersBiz.getOrdersByOrderNum(recieverOrderNum).get(0);
		odr.setAddress(recieverAddress);
		odr.setReceiver(receiver);
		odr.setPhone(recieverPhone);
		//设置订单状态为 卖家已发货
		odr.setStatus("003");
		ordersBiz.update(odr);
		return SUCCESS;
	}
	
	//管理员获取全部订单
	public String ordersShow() {
		Olist = ordersBiz.getAll();
		List<Orders> templist = new ArrayList<Orders>();
		for (Orders orders : Olist) {
			String status = configurationBiz.getStatusByStatusCode(orders.getStatus()).getValue1();
			orders.setStatus(status);
			templist.add(orders);
		}
		Olist = templist;
		return SUCCESS;
	}
	
	//跳转到查看订单页面
	public String ordersView() {
		Integer id = orders.getId();
		orders = ordersBiz.getOrdersById(id);
		return SUCCESS;
	}
		
	//查看订单详情
	@Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}
